using HZY.Core.ScalarAspNetCore;
using HZY.Host.Admin.ApplicationServices.Systems;
using StackExchange.Redis;

namespace HZY.Host.Admin;

/// <summary>
/// 程序启动器
/// </summary>
[ImportStartupModule<
    CoreQuartzStartup,
    CoreRazorStartup,
    CoreRedisStartup,
    CoreIdentityStartup,
    CoreFileStartup,
    AdminRepositoryStartup,
    CoreScalarAspNetCoreJwtStartup,
    SharedAdminStartup>]
public class ApiAdminStartup : AppStartupBase<ApiAdminStartup>
{
    [Value("IsRunQuartzTask")] private bool IsRunQuartzTask { get; } = false;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="webApplicationBuilder"></param>
    public override void ConfigureServices(WebApplicationBuilder webApplicationBuilder)
    {
        base.ConfigureServices(webApplicationBuilder);

        webApplicationBuilder.AddAop();

        var services = webApplicationBuilder.Services;

        services.AddControllers(options =>
            {
                options.Filters.Add<ApiAuthorizationFilter>();
                options.Filters.Add<ApiPermissionFilter>();
            })
            .AddDynamicApiController(options => options.IsLower = false)
            ;

        //SignalR
        services.AddSignalR();

        #region 取消默认验证Api 接收参数模型 的 验证特性 如有 [ApiController]

        services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; });

        #endregion

        services.AddHttpClient("NoCer")
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                return new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = delegate { return true; }
                };
            });

        #region 消息队列

        // webApplicationBuilder.Services.AddCap(x =>
        // {
        //     x.UseDashboard();
        //
        //     //如果你使用的 EF 进行数据操作，你需要添加如下配置：
        //     x.UseEntityFramework<AdminDbContext>(); //可选项，你不需要再次配置 x.UseSqlServer 了
        //
        //     // 内存消息队列
        //     x.UseRedis(opt =>
        //     {
        //         opt.Configuration =
        //             ConfigurationOptions.Parse(configuration.GetSection("ConnectionStrings:Redis").Get<string>());
        //         //opt.Configuration.DefaultDatabase = 3;
        //     });
        //
        //     // x.ConsumerThreadCount = 5; // 同时消费多少个消息
        //     // x.FallbackWindowLookbackSeconds = 2 * 60 * 60;
        //     // x.EnableSubscriberParallelExecute = true;
        //     //x.EnableComsumerPrefetch=
        // });

        #endregion
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="webApplication"></param>
    public override void Configure(WebApplication webApplication)
    {
        base.Configure(webApplication);

        // 跳转客户端
        webApplication.MapGet("/", [AllowAnonymous]() => Results.Redirect("/client/index.html"));

        // 跳转离线文档
        webApplication.MapGet("/docs", [AllowAnonymous]() => Results.Redirect("/docs/index.html"));

        //SignalR
        webApplication.UseSignalRHubs();
    }

    /// <summary>
    /// 程序启动
    /// </summary>
    /// <param name="webApplication"></param>
    public override void ApplicationStarted(WebApplication webApplication)
    {
        // 启动定时任务
        if (IsRunQuartzTask)
        {
            webApplication.UseQuartzStartup();
        }

        // 启动系统监控
        using var scope = webApplication.Services.CreateScope();
        var sysServerService = scope.ServiceProvider.GetRequiredService<SysServerService>();
        sysServerService.InitAsync().Wait();
    }
}